package com.laiketui.admin.store.service.dubbo.systems;

import com.gexin.fastjson.JSON;
import com.gexin.fastjson.TypeReference;
import com.laiketui.admin.store.api.systems.SystemService;
import com.laiketui.common.api.PubliceService;
import com.laiketui.common.mapper.*;
import com.laiketui.common.utils.tool.cache.RedisDataTool;
import com.laiketui.common.utils.tool.data.DataCheckTool;
import com.laiketui.common.utils.tool.str.StringUtils;
import com.laiketui.core.cache.RedisUtil;
import com.laiketui.core.common.SplitUtils;
import com.laiketui.core.exception.LaiKeAPIException;
import com.laiketui.core.lktconst.GloabConst;
import com.laiketui.domain.config.AgreementModel;
import com.laiketui.domain.config.ConfigModel;
import com.laiketui.domain.config.HotKeywordsModel;
import com.laiketui.domain.config.PrintSetupModel;
import com.laiketui.domain.lktconst.DictionaryConst;
import com.laiketui.domain.lktconst.ErrorCode;
import com.laiketui.domain.log.AdminRecordModel;
import com.laiketui.domain.mch.AdminModel;
import com.laiketui.domain.mch.MchModel;
import com.laiketui.domain.systems.SystemConfigurationModel;
import com.laiketui.domain.vo.MainVo;
import com.laiketui.domain.vo.systems.AddSystemVo;
import com.laiketui.domain.vo.systems.SetSystemVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.net.URLDecoder;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 系统配置
 *
 * @author Trick
 * @date 2021/1/15 9:28
 */
@Service
public class SystemServiceImpl implements SystemService {
    private final Logger logger = LoggerFactory.getLogger(SystemServiceImpl.class);

    @Autowired
    private SystemConfigurationModelMapper systemConfigurationModelMapper;

    @Autowired
    private ThirdModelMapper thirdModelMapper;

    @Autowired
    private HotKeywordsModelMapper hotKeywordsModelMapper;

    @Autowired
    private PrintSetupModelMapper printSetupModelMapper;

    @Autowired
    private RedisUtil redisUtil;


    @Override
    public Map<String, Object> getSystemIndex(MainVo vo) throws LaiKeAPIException {
        Map<String, Object> resultMap = new HashMap<>(16);
        try {
            ConfigModel configModel = new ConfigModel();
            configModel.setStore_id(vo.getStoreId());
            configModel = configModelMapper.selectOne(configModel);

            if (configModel != null) {
                configModel.setLogo(publiceService.getImgPath(configModel.getLogo(), vo.getStoreId()));
                configModel.setLogo1(publiceService.getImgPath(configModel.getLogo1(), vo.getStoreId()));
                configModel.setWx_headimgurl(publiceService.getImgPath(configModel.getWx_headimgurl(), vo.getStoreId()));
                if (configModel.getPush_Appid() == null){
                    configModel.setPush_Appid("");
                }
                if (configModel.getPush_Appkey() == null){
                    configModel.setPush_Appkey("");
                }
                if (configModel.getPush_MasterECRET() == null){
                    configModel.setPush_MasterECRET("");
                }
            }
            HotKeywordsModel hotKeywordsModel = new HotKeywordsModel();
            hotKeywordsModel.setStore_id(vo.getStoreId());
            hotKeywordsModel = hotKeywordsModelMapper.selectOne(hotKeywordsModel);
            //订单打印配置
            PrintSetupModel printSetupModel = new PrintSetupModel();
            printSetupModel.setStoreId(vo.getStoreId());
            //管理后台店铺id为0
            printSetupModel.setMchId(0);
            printSetupModel = printSetupModelMapper.selectOne(printSetupModel);
            if (printSetupModel == null){
                printSetupModel = new PrintSetupModel();
            }
            resultMap.put("data", configModel);
            resultMap.put("hotKeywordsConfig", hotKeywordsModel);
            resultMap.put("printSetupConfig", printSetupModel);
        } catch (LaiKeAPIException l) {
            throw l;
        } catch (Exception e) {
            logger.error("获取系统基本配置信息 异常", e);
            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLYC, "网络异常", "getSystemIndex");
        }
        return resultMap;
    }

    @Override
    public boolean addSystemConfig(AddSystemVo vo) throws LaiKeAPIException {
        try {
            AdminModel user = RedisDataTool.getRedisAdminUserCache(vo.getAccessId(), redisUtil);
            int count;
            ConfigModel configModel = new ConfigModel();
            configModel.setStore_id(vo.getStoreId());
            configModel = configModelMapper.selectOne(configModel);

            ConfigModel configModelSave = new ConfigModel();
            configModelSave.setIs_register(StringUtils.toString(vo.getIsRegister()));
            //没有这三个配置 禅道53268 【JAVA开发环境】管理后台（用户管理）：用户设置。头像经常丢失
/*            configModelSave.setLogo(vo.getLogoUrl());
            configModelSave.setLogo1(vo.getWxHeader());
            configModelSave.setWx_headimgurl(vo.getWxHeader());*/
            configModelSave.setH5_domain(vo.getPageDomain());
            configModelSave.setMessage_day(vo.getMessageSaveDay());
            configModelSave.setExp_time(vo.getAppLoginValid());
            configModelSave.setCustomer_service(vo.getServerClient());
            configModelSave.setTencent_key(vo.getTencentKey());
            //默认开启，前端开关按钮隐藏了
            configModelSave.setIs_push(DictionaryConst.WhetherMaven.WHETHER_OK);
            configModelSave.setPush_Appkey(vo.getPushAppkey());
            configModelSave.setPush_Appid(vo.getPushAppid());
            configModelSave.setPush_MasterECRET(vo.getPushMasterEcret());
            configModelSave.setIs_Kicking(vo.getIsKicking());
            configModelSave.setIs_express(vo.getIsExpress());
            configModelSave.setExpress_key(vo.getExpressKey());
            configModelSave.setExpress_number(vo.getExpressNumber());
            configModelSave.setExpress_address(vo.getExpressAddress());

            configModelSave.setWatermark_name(vo.getWatermarkName());
            configModelSave.setWatermark_url(vo.getWatermarkUrl());
            configModelSave.setPc_mch_path(vo.getPcMchPath());
            configModelSave.setExpress_secret(vo.getExpress_secret());
            configModelSave.setExpress_tempId(vo.getExpress_tempId());
            //分账设置
            configModelSave.setIsAccounts(vo.getIsAccounts());
            if (vo.getIsAccounts()==1 && "".equals(vo.getAccountsSet())){
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_MBBCZ, "开启分账必须填写分账账号", "configModelSave");
            }
            configModelSave.setAccountsSet(vo.getAccountsSet());
            //校验数据
            configModelSave = DataCheckTool.checkConfigDataFormate(configModelSave);

            if (configModel != null) {
                //pc店铺默认地址如有修改则需要同步这个商城底下所有店铺的pc端地址
                if (StringUtils.isNotEmpty(configModel.getPc_mch_path()) && !configModel.getPc_mch_path().equals(vo.getPcMchPath())) {
                    synchronizationPcMchPath(vo.getStoreId(), vo.getPcMchPath());
                }
                configModelSave.setIs_register(vo.getIsRegister().toString());
                configModelSave.setId(configModel.getId());
                count = configModelMapper.updateByPrimaryKeySelective(configModelSave);
            } else {
                configModelSave.setStore_id(vo.getStoreId());
                configModelSave.setIs_register(vo.getIsRegister().toString());
                count = configModelMapper.insertSelective(configModelSave);
            }

            HotKeywordsModel hotKeywordsModel = new HotKeywordsModel();
            hotKeywordsModel.setStore_id(vo.getStoreId());
            hotKeywordsModel = hotKeywordsModelMapper.selectOne(hotKeywordsModel);
            Integer isOpen = vo.getIsOpen();
            Integer limitNum = vo.getLimitNum();
            String keyword = vo.getKeyword();
            if (isOpen == 1) {
                if (limitNum == null || limitNum < 1) {
                    throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_SXZSYG, "上限至少一个");
                }
                if (StringUtils.isEmpty(keyword)) {
                    throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_GJZBNWK, "关键词不能为空");
                } else if (keyword.split(SplitUtils.DH).length > limitNum) {
                    throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_GJZBNDYXZSL, "关键词不能大于限制数量");
                }
            }

            HotKeywordsModel hotKeywordsModelSave = new HotKeywordsModel();
            hotKeywordsModelSave.setNum(limitNum);
            hotKeywordsModelSave.setIs_open(isOpen);
            hotKeywordsModelSave.setKeyword(keyword);
            if (hotKeywordsModel != null) {
                hotKeywordsModelSave.setId(hotKeywordsModel.getId());
                count = hotKeywordsModelMapper.updateByPrimaryKeySelective(hotKeywordsModelSave);
            } else {
                hotKeywordsModelSave.setStore_id(vo.getStoreId());
                count = hotKeywordsModelMapper.insertSelective(hotKeywordsModelSave);
            }
            //订单打印配置
            PrintSetupModel printSetupModel = new PrintSetupModel();
            printSetupModel.setStoreId(vo.getStoreId());
            //管理后台店铺id为0
            printSetupModel.setMchId(0);
            printSetupModel = printSetupModelMapper.selectOne(printSetupModel);
            if (printSetupModel != null){
                printSetupModel.setSheng(vo.getSheng());
                printSetupModel.setShi(vo.getShi());
                printSetupModel.setXian(vo.getXian());
                printSetupModel.setAddress(vo.getAddress());
                printSetupModel.setPrintName(vo.getPrintName());
                printSetupModel.setPrintUrl(vo.getPrintUrl());
                printSetupModel.setPhone(vo.getPhone());
                printSetupModelMapper.updateByPrimaryKeySelective(printSetupModel);
            }else {
                printSetupModel = new PrintSetupModel();
                printSetupModel.setStoreId(vo.getStoreId());
                //管理后台店铺id为0
                printSetupModel.setMchId(0);
                printSetupModel.setSheng(vo.getSheng());
                printSetupModel.setShi(vo.getShi());
                printSetupModel.setXian(vo.getXian());
                printSetupModel.setAddress(vo.getAddress());
                printSetupModel.setPrintName(vo.getPrintName());
                printSetupModel.setPrintUrl(vo.getPrintUrl());
                printSetupModel.setPhone(vo.getPhone());
                printSetupModel.setAddTime(new Date());
                count = printSetupModelMapper.insert(printSetupModel);
            }
            //添加操作日志
            publiceService.addAdminRecord(vo.getStoreId(),"修改了基础配置信息",AdminRecordModel.Type.UPDATE,vo.getAccessId());
            return count > 0;
        } catch (LaiKeAPIException l) {
            throw l;
        } catch (Exception e) {
            logger.error("添加/编辑系统配置信息 异常", e);
            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLYC, "网络异常", "addSystemConfig");
        }
    }

    @Override
    public Map<String, Object> getSetSystem(MainVo vo) throws LaiKeAPIException {
        Map<String, Object> resultMap = new HashMap<>(16);
        try {
            SystemConfigurationModel systemConfigurationModel = new SystemConfigurationModel();
            systemConfigurationModel.setStore_id(0);
            systemConfigurationModel = systemConfigurationModelMapper.selectOne(systemConfigurationModel);
            resultMap.put("config", systemConfigurationModel);

            ConfigModel configModel = new ConfigModel();
            configModel.setStore_id(vo.getStoreId());
            configModel = configModelMapper.selectOne(configModel);
            if (configModel != null) {
                resultMap.put("h5Domain", configModel.getH5_domain());
                resultMap.put("domainPath", configModel.getDomain());
            }
        } catch (LaiKeAPIException l) {
            throw l;
        } catch (Exception e) {
            logger.error("获取系统配置 异常", e);
            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLYC, "网络异常", "getSetSystem");
        }
        return resultMap;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void setSystem(SetSystemVo vo) throws LaiKeAPIException {
        try {
            AdminModel adminModel = RedisDataTool.getRedisAdminUserCache(vo.getAccessId(), redisUtil);
            int row;
            if (StringUtils.isEmpty(vo.getLogoUrl())) {
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_DLYBNWK, "登录页logo不能为空");
            }
            if (StringUtils.isEmpty(vo.getCopyrightInformation())) {
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_BQXXBNWK, "版权信息不能为空");
            }
            if (StringUtils.isEmpty(vo.getRecordInformation())) {
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_BAXXBNWK, "备案信息不能为空");
            }
            if (StringUtils.isEmpty(vo.getH5Domain())) {
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_BAXXBNWK, "H5地址不能为空");
            }
            if (StringUtils.isEmpty(vo.getDomainPath())) {
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_BAXXBNWK, "根路径不能为空");
            }
            if (StringUtils.isEmpty(vo.getStoreIdPrefix())){
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_CSCW, "商城ID规则设置不能为空");
            }
            if (StringUtils.isEmpty(vo.getAdminDefaultPortrait())){
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_CSCW, "管理员默认头像不能为空");
            }
            SystemConfigurationModel systemConfigurationOld = null;
            if (vo.getId() != null) {
                systemConfigurationOld = systemConfigurationModelMapper.selectByPrimaryKey(vo.getId());
            }
            SystemConfigurationModel systemConfigurationSave = new SystemConfigurationModel();
            systemConfigurationSave.setLogo(vo.getLogoUrl());
//            systemConfigurationSave.setCopyright_information(vo.getCopyrightInformation());
//            systemConfigurationSave.setRecord_information(vo.getRecordInformation());
            systemConfigurationSave.setStore_id_prefix(vo.getStoreIdPrefix());
            systemConfigurationSave.setAdminDefaultPortrait(vo.getAdminDefaultPortrait());
            //解码
            vo.setLinkPageJson(URLDecoder.decode(vo.getLinkPageJson(), GloabConst.Chartset.UTF_8));
            if (StringUtils.isNotEmpty(vo.getLinkPageJson())) {
                try {
                    JSON.parseObject(vo.getLinkPageJson(), new TypeReference<List<Map<String, Object>>>() {
                    });
                } catch (Exception e) {
                    throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_DLLJCSCW, "登录链接参数错误");
                }
                systemConfigurationSave.setLink_to_landing_page(vo.getLinkPageJson());
            }
            if (systemConfigurationOld == null) {
                systemConfigurationSave.setStore_id(0);
                systemConfigurationSave.setAdd_time(new Date());
                row = systemConfigurationModelMapper.insertSelective(systemConfigurationSave);
            } else {
                systemConfigurationSave.setId(systemConfigurationOld.getId());
                row = systemConfigurationModelMapper.updateByPrimaryKeySelective(systemConfigurationSave);
                //添加操作日志
                publiceService.addAdminRecord(vo.getStoreId(), "修改了系统设置信息",AdminRecordModel.Type.UPDATE, vo.getAccessId());
            }

            if (row < 1) {
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_PZSB, "配置失败");
            }

            ConfigModel configModel = new ConfigModel();
            configModel.setStore_id(vo.getStoreId());
            configModel = configModelMapper.selectOne(configModel);
            if (configModel != null) {
                ConfigModel configModelUpdate = new ConfigModel();
                configModelUpdate.setId(configModel.getId());
                configModelUpdate.setH5_domain(vo.getH5Domain());
                configModelUpdate.setDomain(vo.getDomainPath());
                row = configModelMapper.updateByPrimaryKeySelective(configModelUpdate);
                if (row < 1) {
                    throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_PZSB, "配置失败");
                }
            }else {
                configModel = new ConfigModel();
                configModel.setStore_id(vo.getStoreId());
                configModel.setId(configModel.getId());
                configModel.setH5_domain(vo.getH5Domain());
                configModel.setDomain(vo.getDomainPath());
                row = configModelMapper.insertSelective(configModel);
                if (row < 1) {
                    throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_PZSB, "配置失败");
                }
            }
            //https://java.houjiemeishi.com/# 禅道：43023
            row = thirdModelMapper.updateWorkDomain(vo.getH5Domain());
            if (row < 1){
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_PZSB, "修改后地址配置失败");
            }
        } catch (LaiKeAPIException l) {
            throw l;
        } catch (Exception e) {
            logger.error("系统配置 异常", e);
            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLYC, "网络异常", "setSystem");
        }
    }

    @Override
    public Map<String, Object> getAgreementIndex(MainVo vo, Integer id) throws LaiKeAPIException {
        Map<String, Object> resultMap = new HashMap<>(16);
        try {
            AgreementModel agreementModel = new AgreementModel();
            if (id != null && id > 0) {
                agreementModel.setId(id);
            }
            agreementModel.setStore_id(vo.getStoreId());
            List<AgreementModel> agreementModelList = agreementModelMapper.select(agreementModel);

            resultMap.put("list", agreementModelList);
        } catch (LaiKeAPIException l) {
            throw l;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("获取协议列表 异常" + e.getMessage());
            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLYC, "网络异常", "getAgreementIndex");
        }
        return resultMap;
    }

    @Override
    public void addAgreement(MainVo vo, Integer id, String title, int type, String content) throws LaiKeAPIException {
        try {
            AdminModel user = RedisDataTool.getRedisAdminUserCache(vo.getAccessId(), redisUtil);
            int count;
            if (StringUtils.isEmpty(title)) {
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_XYBTBNWK, "协议标题不能为空");
            }
            if (StringUtils.isEmpty(content)) {
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_NRBNWK, "内容不能为空");
            }
            AgreementModel agreementModel = null;
            if (id != null) {
                agreementModel = agreementModelMapper.selectByPrimaryKey(id);
            }

            AgreementModel agreementModelSave = new AgreementModel();
            agreementModelSave.setName(title);
            agreementModelSave.setType(type);
            agreementModelSave.setContent(content);
            agreementModelSave.setModify_date(new Date());
            String typeName = "";
            //类型 0:注册 1:店铺 2.隐私 3.会员 4.供应商
            if (type==0){
                typeName="注册";
            }else if (type==1){
                typeName="店铺";
            }else if (type==2){
                typeName="隐私";
            }else if (type==3){
                typeName="会员";
            }
            else if (type==4){
                typeName="供应商";
            }
            if (agreementModel != null) {
                agreementModelSave.setId(agreementModel.getId());
                count = agreementModelMapper.updateByPrimaryKeySelective(agreementModelSave);

                //添加操作日志
                publiceService.addAdminRecord(vo.getStoreId(), "修改了"+typeName+"协议信息",AdminRecordModel.Type.UPDATE, vo.getAccessId());

            } else {
                AgreementModel agreementCount = new AgreementModel();
                agreementCount.setStore_id(vo.getStoreId());
                agreementCount.setType(type);
                if (agreementModelMapper.selectCount(agreementCount) > 0) {
                    throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_XYYCZ, "协议已存在");
                }
                agreementModelSave.setStore_id(vo.getStoreId());
                count = agreementModelMapper.insertSelective(agreementModelSave);

                //添加操作日志
                publiceService.addAdminRecord(vo.getStoreId(), "添加了"+typeName+"协议",AdminRecordModel.Type.ADD, vo.getAccessId());
            }
            if (count < 1) {
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_CZSB, "操作失败");
            }
        } catch (LaiKeAPIException l) {
            throw l;
        } catch (Exception e) {
            logger.error("添加/编辑协议 异常", e);
            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLYC, "网络异常", "addAgreement");
        }
    }

    @Override
    public void delAgreement(MainVo vo, int id) throws LaiKeAPIException {
        try {
            AdminModel user = RedisDataTool.getRedisAdminUserCache(vo.getAccessId(), redisUtil);
            AgreementModel agreementModel = agreementModelMapper.selectByPrimaryKey(id);
            if (agreementModel == null) {
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_XYBCZ, "协议不存在");
            }
            if (agreementModelMapper.deleteByPrimaryKey(id) < 1) {
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_CZSB, "操作失败");
            }
            //添加操作日志
            String typeName = "";
            //类型 0:注册 1:店铺 2.隐私 3.会员 4.供应商
            if (agreementModel.getType()==0){
                typeName="注册";
            }else if (agreementModel.getType()==1){
                typeName="店铺";
            }else if (agreementModel.getType()==2){
                typeName="隐私";
            }else if (agreementModel.getType()==3){
                typeName="会员";
            }
            else if (agreementModel.getType()==4){
                typeName="供应商";
            }
            publiceService.addAdminRecord(vo.getStoreId(), "删除了"+typeName+"协议",AdminRecordModel.Type.DEL, vo.getAccessId());
        } catch (LaiKeAPIException l) {
            throw l;
        } catch (Exception e) {
            logger.error("删除协议 异常", e);
            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLYC, "网络异常", "delAgreement");
        }
    }

    @Override
    public boolean updateCommonProblem(MainVo vo, String returnProblem, String payProblem) throws LaiKeAPIException {
        try {
            int count;
            if (StringUtils.isEmpty(returnProblem)) {
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_SHWTBNWK, "售后问题不能为空");
            }
            if (StringUtils.isEmpty(payProblem)) {
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_ZFWTBNWK, "支付问题不能为空");
            }
            ConfigModel configModel = new ConfigModel();
            configModel.setStore_id(vo.getStoreId());
            configModel = configModelMapper.selectOne(configModel);
            if (configModel == null) {
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_QXSZJCPZ, "请先设置基础配置");
            }
            ConfigModel configModelUpdate = new ConfigModel();
            configModelUpdate.setId(configModel.getId());
            configModelUpdate.setPayment_issues(payProblem);
            configModelUpdate.setAfter_sales_issues(returnProblem);
            count = configModelMapper.updateByPrimaryKeySelective(configModelUpdate);

            return count > 0;
        } catch (LaiKeAPIException l) {
            throw l;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("修改常简问题 异常" + e.getMessage());
            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLYC, "网络异常", "updateCommonProblem");
        }
    }

    @Override
    public boolean updateRefundService(MainVo vo, String refundPolicy, String cancelOrderno, String refundMoney, String refundExplain) throws LaiKeAPIException {
        try {
            int count;
            if (StringUtils.isEmpty(refundPolicy)) {
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_THZCBNWK, "退货政策不能为空");
            }
            if (StringUtils.isEmpty(cancelOrderno)) {
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_QXDDBNWK, "取消订单不能为空");
            }
            if (StringUtils.isEmpty(refundMoney)) {
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_TKLCBNWK, "退款流程不能为空");
            }
            if (StringUtils.isEmpty(refundExplain)) {
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_TKSMBNWK, "退款说明不能为空");
            }
            ConfigModel configModel = new ConfigModel();
            configModel.setStore_id(vo.getStoreId());
            configModel = configModelMapper.selectOne(configModel);
            if (configModel == null) {
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_QXSZJCPZ, "请先设置基础配置");
            }
            ConfigModel configModelUpdate = new ConfigModel();
            configModelUpdate.setId(configModel.getId());
            configModelUpdate.setReturn_policy(refundPolicy);
            configModelUpdate.setRefund_process(refundMoney);
            configModelUpdate.setCancellation_order(cancelOrderno);
            configModelUpdate.setRefund_instructions(refundExplain);
            count = configModelMapper.updateByPrimaryKeySelective(configModelUpdate);

            return count > 0;
        } catch (LaiKeAPIException l) {
            throw l;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("修改常简问题 异常" + e.getMessage());
            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLYC, "网络异常", "updateCommonProblem");
        }
    }

    @Override
    public boolean updateBeginnerGuide(MainVo vo, String shoppingProcess, String payType) throws LaiKeAPIException {
        try {
            int count;
            if (StringUtils.isEmpty(shoppingProcess)) {
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_GWLCBNWK, "购物流程不能为空");
            }
            if (StringUtils.isEmpty(payType)) {
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_ZFFSBNWK, "支付方式不能为空");
            }
            ConfigModel configModel = new ConfigModel();
            configModel.setStore_id(vo.getStoreId());
            configModel = configModelMapper.selectOne(configModel);
            if (configModel == null) {
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_QXSZJCPZ, "请先设置基础配置");
            }
            ConfigModel configModelUpdate = new ConfigModel();
            configModelUpdate.setId(configModel.getId());
            configModelUpdate.setPayment_method(payType);
            configModelUpdate.setShopping_process(shoppingProcess);
            count = configModelMapper.updateByPrimaryKeySelective(configModelUpdate);

            return count > 0;
        } catch (LaiKeAPIException l) {
            throw l;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("修改常简问题 异常" + e.getMessage());
            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLYC, "网络异常", "updateCommonProblem");
        }
    }

    @Override
    public boolean updateAboutMe(MainVo vo, String auboutMe) throws LaiKeAPIException {
        try {
            AdminModel user = RedisDataTool.getRedisAdminUserCache(vo.getAccessId(), redisUtil);
            int count;
            if (StringUtils.isEmpty(auboutMe)) {
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_NRBNWK, "内容不能为空");
            }
            ConfigModel configModel = new ConfigModel();
            configModel.setStore_id(vo.getStoreId());
            configModel = configModelMapper.selectOne(configModel);
            if (configModel == null) {
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_QXSZJCPZ, "请先设置基础配置");
            }
            ConfigModel configModelUpdate = new ConfigModel();
            configModelUpdate.setId(configModel.getId());
            configModelUpdate.setAboutus(auboutMe);
            count = configModelMapper.updateByPrimaryKeySelective(configModelUpdate);

            //添加操作日志
            publiceService.addAdminRecord(vo.getStoreId(), "修改了关于我们的内容信息",AdminRecordModel.Type.UPDATE, vo.getAccessId());
            return count > 0;
        } catch (LaiKeAPIException l) {
            throw l;
        } catch (Exception e) {
            logger.error("修改关于我 异常", e);
            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLYC, "网络异常", "updateAboutMe");
        }
    }

    @Override
    public boolean uploadImages(MainVo vo, List<MultipartFile> files) throws LaiKeAPIException {
        try {
            if (files == null || files.size() < 1) {
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_TPBNWK, "图片不能为空");
            }
            //上传图片
            List<String> imagUrls = publiceService.uploadImage(files, GloabConst.UploadConfigConst.IMG_UPLOAD_OSS, vo.getStoreType(), vo.getStoreId());

            logger.debug("图片上传成功,上传{}张,成功{}张", files.size(), imagUrls.size());
            return imagUrls.size() > 0;
        } catch (LaiKeAPIException l) {
            throw l;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("图片上传 异常" + e.getMessage());
            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLYC, "网络异常", "uploadImages");
        }
    }

    @Override
    public boolean updateWeiXinApi(MainVo vo, String appid, String appsecret) throws LaiKeAPIException {
        try {
            int count;
            if (StringUtils.isEmpty(appid)) {
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_XCXBNWK, "小程序appid不能为空");
            }
            if (StringUtils.isEmpty(appsecret)) {
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_XCXMYBNWK, "小程序密钥不能为空");
            }
            ConfigModel configModel = new ConfigModel();
            configModel.setStore_id(vo.getStoreId());
            configModel = configModelMapper.selectOne(configModel);
            if (configModel == null) {
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_QXSZJCPZ, "请先设置基础配置");
            }

            ConfigModel configModelUpdate = new ConfigModel();
            configModelUpdate.setAppid(appid);
            configModelUpdate.setAppsecret(appsecret);
            count = configModelMapper.updateByPrimaryKeySelective(configModelUpdate);

            return count > 0;
        } catch (LaiKeAPIException l) {
            throw l;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("微信小程序配置 异常" + e.getMessage());
            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLYC, "网络异常", "uploadWeiXinApi");
        }
    }


    private void synchronizationPcMchPath(int storeId, String pcMchUrl) throws LaiKeAPIException {
        try {
            MchModel mchModelParam = new MchModel();
            mchModelParam.setStore_id(storeId);
            List<MchModel> mchModelList = mchModelMapper.select(mchModelParam);
            if (mchModelList != null && mchModelList.size() > 0) {
                for (MchModel mchModel : mchModelList){
                    mchModel.setPc_mch_path(pcMchUrl + "/?storeId=" + mchModel.getStore_id());
                    mchModelMapper.updateByPrimaryKeySelective(mchModel);
                }
            }
        } catch (LaiKeAPIException l) {
            throw l;
        } catch (Exception e) {
            logger.error("同步商城所有店铺pc端地址 异常", e);
            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLYC, "网络异常", "synchronizationPcMchPath");
        }
    }

    @Autowired
    private MchModelMapper mchModelMapper;

    @Autowired
    private PubliceService publiceService;

    @Autowired
    private ConfigModelMapper configModelMapper;

    @Autowired
    private AgreementModelMapper agreementModelMapper;
}

